<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="表名">
              <a-input placeholder="请输入表名" v-model="queryParam.tableName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="表类型">
              <j-dict-select-tag
                dictCode="Enumeration,description,enumCode,enumTypeId='cgform_table_type'"
                v-model="queryParam.tableType"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="表描述">
              <a-input placeholder="请输入表描述" v-model="queryParam.tableTxt"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button @click="doCgformButton" type="primary" icon="highlight">自定义按钮</a-button>
      <!--<a-button @click="doEnhanceJs" type="primary" icon="strikethrough">JS增强</a-button>-->
      <!--<a-button @click="doEnhanceSql" type="primary" icon="filter">SQL增强</a-button>-->
      <!--<a-button @click="doEnhanceJava" type="primary" icon="tool">Java增强</a-button>
      <a-button @click="importOnlineForm" type="primary" icon="database">从数据库导入表单</a-button>
      -->
      <a-button @click="goGenerateCode" type="primary" icon="database">代码生成</a-button>

      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"> <a-icon type="delete" />删除 </a-menu-item>
          <a-menu-item key="2" @click="batchExport"> <a-icon type="highlight" />导出xml </a-menu-item>
        </a-menu>
        <a-button>
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i>
        已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>
        项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
      >
        <template slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">
              更多
              <a-icon type="down" />
            </a>
            <a-menu slot="overlay">
              <a-menu-item v-if="record.isDbSynch != 'Y'">
                <a @click="openSyncModal(record.id)">同步数据库</a>
              </a-menu-item>

              <template v-if="record.isDbSynch == 'Y' && record.tableType !== 3">
                <a-menu-item>
                  <a @click="goPageOnline(record)">功能测试</a>
                </a-menu-item>
                <a-menu-item>
                  <a @click="handleOnlineUrlShow(record)">配置地址</a>
                </a-menu-item>
              </template>

              <a-menu-item>
                <a @click="copyConfig(record.id)">复制视图</a>
              </a-menu-item>

              <a-menu-item v-if="record.hascopy == 1">
                <a @click="showMyCopyInfo(record.id)">配置视图</a>
              </a-menu-item>

              <a-menu-item>
                <a @click="handleRemoveRecord(record.id)">移除</a>
              </a-menu-item>

              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>

        <template slot="dbsync" slot-scope="text">
          <span v-if="text === 'Y'" style="color: limegreen">已同步</span>
          <span v-if="text === 'N'" style="color: red">未同步</span>
        </template>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->

    <a-modal title="新增" :visible="dialogFormVisible" :width="1400" @ok="show" @cancel="dialogFormVisible = false">
      <a-form-model :model="head" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row>
          <a-col :span="24">
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="表名">
                  <a-input v-model="head.tableName" placeholder="请输入表名" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="表描述">
                  <a-input v-model="head.tableTxt" placeholder="请输入表描述" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="表类型">
                  <a-select v-model="head.tableType" @change="changeTableType">
                    <a-select-option value="1">单表</a-select-option>
                    <a-select-option value="2">主表</a-select-option>
                    <a-select-option value="3">附表</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row v-if="head.tableType == '3'">
              <a-col :span="4" class="ant-col-push-17" style="left: 69.833333%">
                <a-form-model-item>
                  <a-radio-group style="width: 100%" v-model="head.relationType" :default-value="0">
                    <a-radio value="0"> 一对多 </a-radio>
                    <a-radio value="1"> 一对一 </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col :span="3" class="ant-col-push-17" style="left: 67.833333%">
                <a-form-model-item>
                  序号<a-input-number v-model="head.tabOrderNum" :max="10" style="width: 88px" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="表单分类">
              <a-select v-model="head.formCategory" placeholder="请选择表单分类">
                <a-select-option value="bdfl_include">导入表单</a-select-option>
                <a-select-option value="2">普通表单</a-select-option>
                <a-select-option value="3">复杂表单</a-select-option>
                <a-select-option value="4">VIP表单</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="主键策略">
              <a-select v-model="head.idSequence" placeholder="请选择主键策略">
                <a-select-option value="1">主键自增</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="查询模式">
              <a-select v-model="head.queryMode" placeholder="请选择查询模式">
                <a-select-option value="single">单表查询</a-select-option>
                <a-select-option value="2">组合查询</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="默认主题">
              <a-select v-model="head.themeTemplate" placeholder="请选择默认主题">
                <a-select-option value="normal">默认主题</a-select-option>
                <a-select-option value="erp">ERP(一对多)</a-select-option>
                <a-select-option value="innerTable">内嵌表</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="表单风格">
              <a-select v-model="head.formTemplateMobile" placeholder="请选择表单风格">
                <a-select-option value="24">一列</a-select-option>
                <a-select-option value="12">两列</a-select-option>
                <a-select-option value="8">三列</a-select-option>
                <a-select-option value="6">四列</a-select-option>
                <!-- <a-select-option value="5">自适应</a-select-option> -->
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="滚动条">
              <a-select v-model="head.autoScroll" placeholder="请选择有无滚动条">
                <a-select-option value="1">有</a-select-option>
                <a-select-option value="0">无</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="显示复选框">
              <a-select v-model="head.isCheckbox" placeholder="please select your zone">
                <a-select-option value="Y">是</a-select-option>
                <a-select-option value="N">否</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="是否分页">
              <a-select v-model="head.isPage" placeholder="please select your zone">
                <a-select-option value="Y">是</a-select-option>
                <a-select-option value="N">否</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="是否树">
              <a-select v-model="head.isTree" @change="treeAdd" placeholder="please select your zone">
                <a-select-option value="Y">是</a-select-option>
                <a-select-option value="N">否</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" style="left: -1.5%" v-if="head.tableType == '2'">
            <a-form-model-item :labelCol="labelCol2" :wrapperCol="wrapperCol2" label="附表">
              <a-input v-model="head.subTableStr" style="width: 98.5%" :disabled="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="head.isTree == 'Y'">
            <a-form-model-item label="树表单父ID">
              <a-input v-model="head.treeParentIdField" placeholder="请输入树表单父ID字段名" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="head.isTree == 'Y'">
            <a-form-model-item label="树开表单列">
              <a-input v-model="head.treeFieldname" placeholder="请输入树开表单列字段名" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="head.isTree == 'Y'">
            <a-form-model-item label="是否有子节点">
              <a-input v-model="head.treeIdField" placeholder="请输入是否有子节点字段名" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <div>
        <a-tabs default-active-key="1" @change="callback">
          <a-tab-pane key="1" tab="数据库属性">
            <j-editable-table
              ref="editableTable"
              :loading="loading"
              :columns="columnsDatabase"
              :disabledRows="disabledRows"
              :dataSource="fields"
              :rowNumber="true"
              :rowSelection="true"
              :actionButton="true"
              :dragSort="true"
              :maxHeight="400"
              style="margin-top: 8px"
              @added="add"
              @deleted="deleted"
              @valueChange="handleValueChange"
              @dragged="handDragged"
            ></j-editable-table>
          </a-tab-pane>
          <a-tab-pane key="2" tab="页面属性">
            <j-editable-table
              ref="editableTable2"
              :columns="columnsAttr"
              :dataSource="fields"
              :rowNumber="true"
              :rowSelection="false"
              :actionButton="false"
              :dragSort="false"
              style="margin-top: 8px"
              @valueChange="handleValueChange"
            ></j-editable-table>
          </a-tab-pane>
          <a-tab-pane key="3" tab="校验字段">
            <j-editable-table
              ref="editableTable3"
              :columns="columnsValidate"
              :dataSource="fields"
              :rowNumber="true"
              :maxHeight="400"
              @valueChange="handleValueChange"
            />
          </a-tab-pane>
          <a-tab-pane key="4" tab="外键">
            <j-editable-table
              ref="editableTable4"
              :columns="columnsForeign"
              :dataSource="fields"
              :rowNumber="true"
              :maxHeight="400"
              @valueChange="handleValueChange"
            />
          </a-tab-pane>
          <a-tab-pane key="5" tab="索引">
            <j-editable-table
              ref="editableTable5"
              :loading="loading"
              :columns="columnsIndex"
              :dataSource="indexs"
              :rowNumber="true"
              :rowSelection="true"
              :actionButton="true"
              style="margin-top: 8px"
              @added="addIndex"
              @deleted="deletedIndex"
              @valueChange="handleIndexChange"
            ></j-editable-table>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-modal>

    <!-- 同步数据库提示框 -->
    <a-modal
      :width="500"
      :height="300"
      title="同步数据库"
      :visible="syncModalVisible"
      @cancel="handleCancleDbSync"
      style="top: 5%; height: 95%"
    >
      <template slot="footer">
        <a-button @click="handleCancleDbSync">关闭</a-button>
        <a-button type="primary" :loading="syncLoading" @click="handleDbSync">确定</a-button>
      </template>
      <a-radio-group v-model="synMethod">
        <a-radio style="display: block; width: 30px; height: 30px" value="headNormal">普通同步(保留表数据)</a-radio>
        <a-radio style="display: block; width: 30px; height: 30px" value="headForce">强制同步(删除表,重新生成)</a-radio>
      </a-radio-group>
    </a-modal>

    <!-- 提示online报表链接 -->
    <a-modal :title="onlineUrlTitle" :visible="onlineUrlVisible" @cancel="handleOnlineUrlClose">
      <template slot="footer">
        <a-button @click="handleOnlineUrlClose">关闭</a-button>
        <a-button type="primary" class="copy-this-text" :data-clipboard-text="onlineUrl" @click="onCopyUrl"
          >复制</a-button
        >
      </template>
      <p>{{ onlineUrl }}</p>
    </a-modal>

    <!--
    <enhance-js ref="ehjs"></enhance-js>
    <enhance-sql ref="ehsql"></enhance-sql>
    <enhance-java ref="ehjava"></enhance-java>
    <trans-db2-online ref="transd2o" @ok="transOk"></trans-db2-online>

    <onl-cgform-button-list ref="btnList"></onl-cgform-button-list>
    -->
    <code-generator ref="cg"></code-generator>
  </a-card>
</template>

<script>
import { initDictOptions, filterDictText } from '@/components/dict/JDictSelectUtil'
import { deleteAction, postAction, postTokenAction, downXmlFile } from '@/api/manage'
import JDictSelectTag from '../../../../components/dict/JDictSelectTag.vue'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import Clipboard from 'clipboard'
import { filterObj } from '@/utils/util'
import CodeGenerator from './modules/CodeGenerator'
import JEditableTable from '@/components/jeecg/JEditableTable'
import { FormTypes } from '@/utils/JEditableTableUtil'

export default {
  name: 'OufuFormHeadList',
  mixins: [JeecgListMixin],
  components: {
    JDictSelectTag,
    JEditableTable,
    CodeGenerator,
  },
  data() {
    return {
      dialogFormVisible: false,
      labelCol: { span: 5 },
      wrapperCol: { span: 14 },

      labelCol2: {
        xs: { span: 24 },
        sm: { span: 2 },
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 21 },
      },

      newForm: {
        tableName: '',
        tableTxt: '',
        tableType: '1',
        relationType: '0',
        formCategory: 'bdfl_include',
        idSequence: '1',
        queryMode: 'single',
        themeTemplate: 'normal',
        formTemplateMobile: '12',
        autoScroll: '0',
        isCheckbox: 'Y',
        isPage: 'Y',
        isTree: 'N',
        treeParentIdField: '',
        treeIdField: '',
        treeFieldname: '',

        tableVersion: 1,
        formTemplate: 1,
        copyType: 0,
        isDbSynch: 'N',
        hascopy: 0,
        idType: 'UUID',
      },
      loading: false,
      columnsDatabase: [
        {
          title: '字段名称',
          key: 'dbFieldName',
          type: FormTypes.input,
          placeholder: '请输入${title}',
          validateRules: [
            {
              required: true, // 必填
              message: '请输入${title}', // 显示的文本
            },
            {
              unique: true,
              message: '${title}不能重复',
            },
            {
              handler(type, value, row, column, callback, target) {
                if (type === 'blur') {
                  if (value === 'abc') {
                    callback(false, '${title}不能是abc') // false = 未通过校验
                  } else {
                    callback(true) // true = 通过验证
                  }
                } else {
                  callback(true) // 不填写或者填写 null 代表不进行任何操作
                }
              },
              message: '${title}默认提示',
            },
          ],
        },
        {
          title: '字段备注',
          key: 'dbFieldTxt',
          type: FormTypes.input,
          placeholder: '请输入${title}',
        },
        {
          title: '字段长度',
          key: 'dbLength',
          type: FormTypes.input,
          placeholder: '请输入${title}',
        },
        {
          title: '小数点',
          key: 'dbPointLength',
          type: FormTypes.input,
          placeholder: '请输入${title}',
        },
        {
          title: '默认值',
          key: 'dbDefaultVal',
          type: FormTypes.input,
          placeholder: '请输入${title}',
        },
        {
          title: '字段类型',
          key: 'dbType',
          width: '150px',
          type: FormTypes.select,
          options: [
            // 下拉选项
            { title: 'String', value: 'String' },
            { title: 'Numeric', value: 'Numeric' },
            { title: 'Date', value: 'Date' },
            { title: 'BigDecimal', value: 'BigDecimal' },
            { title: 'Text', value: 'Text' },
            { title: 'Blob', value: 'Blob' },
          ],
          allowInput: false,
          defaultValue: 'string',
          placeholder: '请选择${title}',
        },
        {
          title: '主键',
          key: 'dbIsKey',
          type: FormTypes.checkbox,
          customValue: [true, false], // true ,false
          defaultChecked: false,
        },
        {
          title: '是否为空',
          key: 'dbIsNull',
          type: FormTypes.checkbox,
          customValue: [true, false], // true ,false
          defaultChecked: false,
        },
      ],
      columnsAttr: [
        {
          title: '字段名称',
          key: 'dbFieldName',
          type: FormTypes.input,
          defaultValue: '',
          disabled: true,
        },
        {
          title: '字段备注',
          key: 'dbFieldTxt',
          type: FormTypes.input,
          disabled: true,
        },
        {
          title: '表单显示',
          key: 'isShowForm',
          type: FormTypes.checkbox,
          placeholder: '请选择${title}',
          customValue: [true, false], // true ,false
          defaultChecked: false,
        },
        {
          title: '列表显示',
          key: 'isShowList',
          type: FormTypes.checkbox,
          placeholder: '请选择${title}',
          customValue: [true, false], // true ,false
          defaultChecked: false,
        },
        {
          title: '是否只读',
          key: 'isReadOnly',
          type: FormTypes.checkbox,
          placeholder: '请选择${title}',
          customValue: [true, false], // true ,false
          defaultChecked: false,
        },
        {
          title: '控件类型',
          key: 'fieldShowType',
          width: '150px',
          type: FormTypes.select,
          options: [
            // 下拉选项
            {
              title: '文本框',
              value: 'text',
            },
            {
              title: '密码',
              value: 'password',
            },
            {
              title: '单选框',
              value: 'radio',
            },
            {
              title: '多选',
              value: 'checkbox',
            },
            {
              title: '日期(yyyy-MM-dd)',
              value: 'date',
            },
            {
              title: '日期（yyyy-MM-dd HH:mm:ss）',
              value: 'datetime',
            },
            {
              title: '文件',
              value: 'file',
            },
            {
              title: '图片',
              value: 'image',
            },
            {
              title: '多行文本',
              value: 'textarea',
            },
            {
              title: '下拉框',
              value: 'list',
            },
            {
              title: '下拉多选框',
              value: 'list_multi',
            },
            {
              title: '下拉搜索框',
              value: 'sel_search',
            },
            {
              title: '自定义树控件',
              value: 'sel_tree',
            },
            {
              title: '分类字典树',
              value: 'cat_tree',
            },
            {
              title: 'popup弹出框',
              value: 'popup',
            },
            {
              title: '富文本编辑器',
              value: 'umeditor',
            },
          ],
          allowInput: false,
          defaultValue: 'text',
          placeholder: '请选择${title}',
        },
        {
          title: '控件长度',
          key: 'fieldLength',
          type: FormTypes.input,
          defaultValue: '120',
        },
        {
          title: '是否查询',
          key: 'isQuery',
          type: FormTypes.checkbox,
          customValue: [true, false], // true ,false
          defaultChecked: false,
        },
        {
          title: '查询类型',
          key: 'queryMode',
          type: FormTypes.select,
          options: [
            // 下拉选项
            { title: '普通查询', value: 'single' },
            { title: '范围查询', value: '?' },
          ],
          defaultValue: 'normalArea',
        },
        {
          title: '拓展参数',
          key: 'fieldExtendJson',
          type: FormTypes.input,
        },
        {
          title: '填值规则',
          key: 'fieldValueRuleCode',
          type: FormTypes.input,
        },
      ],
      columnsValidate: [
        {
          title: '字段名称',
          key: 'dbFieldName',
          type: FormTypes.input,
          defaultValue: '',
          disabled: true,
        },
        {
          title: '字段备注',
          key: 'dbFieldTxt',
          type: FormTypes.input,
          disabled: true,
        },
        {
          title: '字段Href',
          key: 'fieldHref',
          type: FormTypes.input,
          placeholder: '请输入${title}',
        },
        {
          title: '检验规则',
          key: 'fieldValidType',
          type: FormTypes.select,
          options: [
            // 下拉选项
            {
              title: '空',
              value: '',
            },
            {
              title: '唯一校验',
              value: 'only',
            },
            {
              title: '6到16位数字',
              value: 'n6-16',
            },
            {
              title: '6到16位任意字符',
              value: '*6-16',
            },
            {
              title: '网址',
              value: 'url',
            },
            {
              title: '电子邮件',
              value: 'e',
            },
            {
              title: '手机号码',
              value: 'm',
            },
            {
              title: '邮政编码',
              value: 'p',
            },
            {
              title: '字母',
              value: 's',
            },
            {
              title: '数字',
              value: 'n',
            },
            {
              title: '整数',
              value: 'z',
            },
            {
              title: '非空',
              value: '*',
            },
            {
              title: '6到18位字符串',
              value: 's6-18',
            },
            {
              title: '金额',
              value: 'money',
            },
          ],
          defaultValue: '',
          allowInput: false,
        },
        {
          title: '校验必填',
          key: 'fieldMustInput',
          type: FormTypes.checkbox,
          placeholder: '请选择${title}',
          customValue: [true, false], // true ,false
          defaultChecked: false,
        },
        {
          title: '字典Table',
          key: 'dictTable',
          type: FormTypes.input,
        },
        {
          title: '字典Code',
          key: 'dictField',
          type: FormTypes.input,
        },
        {
          title: '字典Text',
          key: 'dictText',
          type: FormTypes.input,
        },
      ],
      columnsForeign: [
        {
          title: '字段名称',
          key: 'dbFieldName',
          type: FormTypes.input,
          disabled: true,
        },
        {
          title: '字段备注',
          key: 'dbFieldTxt',
          type: FormTypes.input,
          disabled: true,
        },
        {
          title: '主表名',
          key: 'mainTable',
          type: FormTypes.input,
          defaultValue: '',
        },
        {
          title: '主表字段',
          key: 'mainField',
          type: FormTypes.input,
          defaultValue: '',
        },
      ],
      columnsIndex: [
        {
          title: '索引名称',
          key: 'indexName',
          type: FormTypes.input,
          defaultValue: '',
          placeholder: '请选择${title}',
        },
        {
          title: '索引栏位',
          key: 'indexField',
          width: '150px',
          type: FormTypes.select,
          options: [],
          allowInput: false,
          placeholder: '请选择${title}',
        },
        {
          title: '字段类型',
          key: 'indexType',
          width: '150px',
          type: FormTypes.select,
          options: [
            // 下拉选项
            { title: 'normal', value: 'normal' },
            { title: 'unique', value: 'unique' },
          ],
          allowInput: false,
          defaultValue: 'normal',
        },
      ],
      selectedRowIds: [],

      formLabelWidth: '120px',
      description: 'Online表单开发管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '表类型',
          align: 'center',
          dataIndex: 'tableType',
          customRender: (text, record) => {
            let tbTypeText = filterDictText(this.tableTypeDictOptions, `${text}`)
            if (record.isTree === 'Y') {
              tbTypeText += '(树)'
            }
            return tbTypeText
          },
        },
        {
          title: '表名',
          align: 'center',
          dataIndex: 'tableName',
        },
        {
          title: '表描述',
          align: 'center',
          dataIndex: 'tableTxt',
        },
        {
          title: '版本',
          align: 'center',
          dataIndex: 'tableVersion',
        },

        {
          title: '同步数据库状态',
          align: 'center',
          dataIndex: 'isDbSynch',
          scopedSlots: { customRender: 'dbsync' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/online/public/autoApiListEntity', //Y

        delete: '/online/cgform/headDelete', //Y
        deleteBatch: '/online/cgform/headDeleteBatch', //Y
        doDbSynch: '/online/cgform/doDbSynch/',
        removeRecord: '/online/cgform/headRemoveRecord', //Y
        copyOnline: '/online/cgform/headCopyOnline',
        autoGetColumns: '/online/public/autoGetColumns', //Y
        listByHeadId: '/online/cgform/listByHeadId', //Y

        add: '/online/cgform/special/api/apiAddAll',
        edit: '/online/cgform/special/api/apiEditAll',
      },
      tableTypeDictOptions: [],
      sexDictOptions: [],
      syncModalVisible: false,
      syncFormId: '',
      synMethod: 'headNormal',
      syncLoading: false,
      onlineUrlTitle: '',
      onlineUrlVisible: false,
      onlineUrl: '',
      selectedRowKeys: [],
      selectedRows: [],
      addFiledList: [
        {
          dbFieldName: 'id',
          dbFieldTxt: '主键',
          dbLength: 60,
          dbPointLength: 0,
          dbDefaultVal: '',
          dbType: 'String',
          dbIsKey: true,
          dbIsNull: false,
          isShowForm: false,
          isShowList: false,
          isReadOnly: true,
          fieldShowType: 'text',
          fieldLength: 120,
          isQuery: false,
          queryMode: 'single',
          fieldExtendJson: '',
          fieldValueRuleCode: '',
          fieldHref: '',
          fieldValidType: '',
          fieldMustInput: true,
          dictTable: '',
          dictField: '',
          dictText: '',
          mainTable: '',
          mainField: '',
          indexName: '',
          indexValue: '',
          indexType: 'normal',
        },
      ],
      addTreeId: [],
      addTreeList: [
        {
          //id:'parentId',
          dbFieldName: 'parentId',
          dbFieldTxt: '父级节点',
          dbLength: 60,
          dbPointLength: 0,
          dbDefaultVal: '',
          dbType: 'String',
          dbIsKey: false,
          dbIsNull: true,
          isShowForm: false,
          isShowList: false,
          isReadOnly: false,
          fieldShowType: 'text',
          fieldLength: 120,
          isQuery: false,
          queryMode: 'single',
          fieldExtendJson: '',
          fieldValueRuleCode: '',
          fieldHref: '',
          fieldValidType: '',
          fieldMustInput: false,
          dictTable: '',
          dictField: '',
          dictText: '',
          mainTable: '',
          mainField: '',
          indexName: '',
          indexValue: '',
          indexType: 'normal',
        },
        {
          //id:'hasChild',
          dbFieldName: 'hasChild',
          dbFieldTxt: '是否有子节点',
          dbLength: 5,
          dbPointLength: 0,
          dbDefaultVal: '',
          dbType: 'String',
          dbIsKey: false,
          dbIsNull: true,
          isShowForm: false,
          isShowList: false,
          isReadOnly: false,
          fieldShowType: 'text',
          fieldLength: 120,
          isQuery: false,
          queryMode: 'single',
          fieldExtendJson: '',
          fieldValueRuleCode: '',
          fieldHref: '',
          fieldValidType: '',
          fieldMustInput: false,
          dictTable: '',
          dictField: '',
          dictText: '',
          mainTable: '',
          mainField: '',
          indexName: '',
          indexValue: '',
          indexType: 'normal',
        },
      ],

      disabledRows: {},
      head: {},
      fields: [],
      indexs: [],
      deleteFieldIds: [],
      deleteIndexIds: [],
    }
  },
  computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.name === 'Disabled User', // Column configuration not to be checked
            name: record.name,
          },
        }),
      }
    },
  },
  created() {
    //初始化字典 - 表类型
    initDictOptions("Enumeration,description,enumCode,enumTypeId='cgform_table_type'").then((res) => {
      if (res.success) {
        this.tableTypeDictOptions = res.result
      }
    })
  },
  methods: {
    handDragged(data) {
      data.target.inputValues.forEach((item) => {
        this.fields.forEach((item2) => {
          if (item.dbFieldName == item2.dbFieldName) {
            item2.orderNum = item.orderNum
          }
        })
      })
    },
    batchExport() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        //导出操作
        downXmlFile('/online/api/autoXmlExport', { ids: ids }).then((data) => {
          if (!data) {
            this.$message.warning('文件下载失败')
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data.result]), this.description + '.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data.result]))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', '表单数据.xml')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) //下载完成移除元素
            window.URL.revokeObjectURL(url) //释放掉blob对象
          }
        })
      }
    },
    changeTableType(val) {},
    handleAdd() {
      this.dialogFormVisible = true
      //清空字段
      this.fields = []
      this.indexs = []
      this.deleteFieldIds = []
      this.deleteIndexIds = []
      this.head = Object.assign({}, this.newForm)
      this.addFiledList.forEach((item) => {
        this.fields.push(item)
      })
      this.indexOptions()
      //主键不可更改
      this.disabledRows = { dbFieldName: 'id' }
    },
    indexOptions() {
      let options = []
      this.fields.forEach((item) => {
        options.push({ title: item.dbFieldName, value: item.dbFieldName })
      })
      this.columnsIndex[1].options = options
    },
    handleEdit(record) {
      this.dialogFormVisible = true
      this.deleteFieldIds = []
      this.deleteIndexIds = []
      this.head = record
      this.head.tableVersion = this.head.tableVersion + 1
      //请求字段
      postAction(this.url.listByHeadId, { autoHeadId: record.id, typeId: 'field' }).then((res) => {
        if (res.success) {
          this.fields = res.result
          let options = []
          this.fields.forEach((item) => {
            options.push({ title: item.dbFieldName, value: item.dbFieldName })
          })
          this.columnsIndex[1].options = options
        }
      })
      //请求索引
      postAction(this.url.listByHeadId, { autoHeadId: record.id, typeId: 'index' }).then((res) => {
        if (res.success) {
          this.indexs = res.result
        }
      })

      //主键不可更改
      this.disabledRows = { dbFieldName: 'id' }
    },

    treeAdd(val) {
      if (val == 'Y') {
        if (this.addTreeId.length == 0) {
          this.addTreeList.forEach((item) => {
            this.fields.push(item)
            this.addTreeId.push((this.$refs.editableTable.caseId = item.dbFieldName))
          })
          this.head.treeParentIdField = 'parentId'
          this.head.treeIdField = 'hasChild'
        }
      } else {
        if (this.addTreeId.length != 0) {
          this.$refs.editableTable.removeRows(this.addTreeId)
          this.addTreeId = []
          this.head.treeParentIdField = ''
          this.head.treeIdField = ''
        }
      }
    },
    handleValueChange(event) {
      const { type, row, column, value, target } = event
      this.fields.forEach((item) => {
        if (item.id == row.id) {
          item[column.key] = value
        }
      })
      this.indexOptions()
    },
    handleIndexChange(event) {
      const { type, row, column, value, target } = event
      this.indexs.forEach((item) => {
        if (item.id == row.id) {
          item[column.key] = value
        }
      })
    },
    //删除字段属性
    deleted(ids) {
      ids.forEach((item) => {
        this.deleteFieldIds.push(item)
      })
      this.indexOptions()
    },
    //增加字段属性
    add(r) {
      this.fields.push({
        id: r.row.id,
        dbFieldName: '',
        dbFieldTxt: '',
        dbLength: 60,
        dbPointLength: 0,
        dbDefaultVal: '',
        dbType: 'String',
        dbIsKey: false,
        dbIsNull: true,
        isShowForm: true,
        isShowList: true,
        isReadOnly: false,
        fieldShowType: 'text',
        fieldLength: 120,
        isQuery: false,
        queryMode: 'single',
        fieldExtendJson: '',
        fieldValueRuleCode: '',
        fieldHref: '',
        fieldValidType: '',
        fieldMustInput: false,
        dictTable: '',
        dictField: '',
        dictText: '',
        mainTable: '',
        mainField: '',
        indexName: '',
        indexValue: '',
        indexType: 'normal',
      })
    },
    //增加索引
    addIndex(r) {
      this.indexs.push({
        id: r.row.id,
        indexName: '',
        indexField: '',
        indexType: 'normal',
      })
    },
    //删除索引
    deletedIndex(ids) {
      ids.forEach((item) => {
        this.deleteIndexIds.push(item)
      })
    },
    dragged(e) {},
    show() {
      let fields = []
      this.fields.forEach((item) => {
        let newItem = Object.assign({}, item)
        if (newItem.dbIsKey == true) {
          newItem.dbIsKey = 1
        } else {
          newItem.dbIsKey = 0
        }
        if (newItem.dbIsNull == true) {
          newItem.dbIsNull = 1
        } else {
          newItem.dbIsNull = 0
        }
        if (newItem.isShowForm == true) {
          newItem.isShowForm = 1
        } else {
          newItem.isShowForm = 0
        }
        if (newItem.isShowList == true) {
          newItem.isShowList = 1
        } else {
          newItem.isShowList = 0
        }
        if (newItem.isReadOnly == true) {
          newItem.isReadOnly = 1
        } else {
          newItem.isReadOnly = 0
        }
        if (newItem.isQuery == true) {
          newItem.isQuery = 1
        } else {
          newItem.isQuery = 0
        }
        if (newItem.isSorter == true) {
          newItem.isSorter = 1
        } else {
          newItem.isSorter = 0
        }
        if (newItem.fieldMustInput == true) {
          newItem.fieldMustInput = 1
        } else {
          newItem.fieldMustInput = 0
        }
        fields.push(newItem)
      })
      console.log(this)
      let parameters = {
        head: this.head,
        fields: fields,
        indexs: this.indexs,
        deleteFieldIds: this.deleteFieldIds,
        deleteIndexIds: this.deleteIndexIds,
      }
      let url = this.url.add
      if (this.head.id) {
        url = this.url.edit
      }
      postTokenAction(url, parameters).then((res) => {
        if (res.success) {
          //创建成功
          this.dialogFormVisible = false
          //刷新页面
          this.searchQuery()
        }
      })
    },

    callback(key) {},

    doDbSynch(id) {
      postAction(this.url.doDbSynch + id, { synMethod: '1' }).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    getQueryParams() {
      //获取查询条件
      var param = Object.assign({}, this.queryParam, this.isorter, this.filters)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      param.copyType = 0
      param.delFlag = 'N'
      param.entityName = 'OnlScFormHead'
      return filterObj(param)
    },
    handleCancleDbSync() {
      this.syncModalVisible = false
    },
    handleDbSync() {
      this.syncLoading = true
      postAction(this.url.doDbSynch + this.syncFormId + '/' + this.synMethod, { autoHeadId: this.syncFormId }).then(
        (res) => {
          this.syncModalVisible = false
          this.syncLoading = false
          if (res.success) {
            this.$message.success(res.message)
            this.loadData()
          } else {
            this.$message.warning(res.message)
          }
        }
      )
      setTimeout(() => {
        if (this.syncLoading) {
          this.syncModalVisible = false
          this.syncLoading = false
          this.$message.success('网络延迟,已自动刷新!')
          this.loadData()
        }
      }, 10000)
    },
    openSyncModal(id) {
      this.syncModalVisible = true
      this.syncLoading = false
      this.syncFormId = id
    },
    goPageOnline(rd) {
      // 分3中情况默认 erp一对多 子表内嵌
      if (rd.tableType == '2') {
        if (rd.themeTemplate === 'erp') {
          this.$router.push({ path: '/online/oufuformErpList/' + rd.id })
        } else if (rd.themeTemplate === 'innerTable') {
          this.$router.push({ path: '/online/oufuformInnerTableList/' + rd.id })
        } else {
          this.$router.push({ path: '/online/oufuformOneToManyList/' + rd.id })
        }
      } else {
        //1
        if (rd.isTree == 'Y') {
          this.$router.push({ path: '/online/oufuformTreeList/' + rd.id })
        } else {
          this.$router.push({ path: '/online/oufuformList/' + rd.id })
        }
      }
    },
    handleOnlineUrlClose() {
      this.onlineUrlTitle = ''
      this.onlineUrlVisible = false
    },
    handleOnlineUrlShow(record) {
      if (record.isTree == 'Y') {
        this.onlineUrl = `/online/oufuformTreeList/${record.id}`
      } else {
        this.onlineUrl = `/online/oufuformList/${record.id}`
      }
      this.onlineUrlVisible = true
      this.onlineUrlTitle = '菜单链接[' + record.tableTxt + ']'
    },
    handleRemoveRecord(id) {
      let that = this
      this.$confirm({
        title: '确认要移除此记录?',
        onOk() {
          deleteAction(that.url.removeRecord, { id: id }).then((res) => {
            if (res.success) {
              that.$message.success('移除成功')
              that.loadData()
            } else {
              that.$message.warning(res.message)
            }
          })
        },
        onCancel() {},
      })
    },
    doEnhanceJs() {
      if (!this.selectedRowKeys || this.selectedRowKeys.length != 1) {
        this.$message.warning('请先选中一条记录')
        return
      }
      this.$refs.ehjs.show(this.selectedRowKeys[0])
    },
    doEnhanceSql() {
      if (!this.selectedRowKeys || this.selectedRowKeys.length != 1) {
        this.$message.warning('请先选中一条记录')
        return
      }
      this.$refs.ehsql.show(this.selectedRowKeys[0])
    },
    doEnhanceJava() {
      if (!this.selectedRowKeys || this.selectedRowKeys.length != 1) {
        this.$message.warning('请先选中一条记录')
        return
      }
      this.$refs.ehjava.show(this.selectedRowKeys[0])
    },
    doCgformButton() {
      if (!this.selectedRowKeys || this.selectedRowKeys.length != 1) {
        this.$message.warning('请先选中一条记录')
        return
      }
      this.$refs.btnList.show(this.selectedRowKeys[0])

      //this.$router.push({ path: '/online/cgformButton/' + this.selectedRowKeys[0] })
    },
    importOnlineForm() {
      this.$refs.transd2o.show()
    },
    transOk() {
      this.loadData()
    },
    goGenerateCode() {
      if (!this.selectedRowKeys || this.selectedRowKeys.length != 1) {
        this.$message.warning('请先选中一条记录')
        return
      }
      let row = this.selectedRows[0]
      if (!row.isDbSynch || row.isDbSynch == 'N') {
        this.$message.warning('请先同步数据库!')
        return
      }
      if (row.tableType == 3) {
        this.$message.warning('请选中该表对应的主表生成代码')
        return
      }
      this.$refs.cg.show(this.selectedRowKeys[0])
    },
    onSelectChange(keys, rows) {
      this.selectedRowKeys = keys
      this.selectedRows = rows
    },
    onCopyUrl() {
      var clipboard = new Clipboard('.copy-this-text')
      clipboard.on('success', () => {
        clipboard.destroy()
        this.$message.success('复制成功')
        this.handleOnlineUrlClose()
      })
      clipboard.on('error', () => {
        this.$message.error('该浏览器不支持自动复制')
        clipboard.destroy()
      })
    },
    showMyCopyInfo(id) {
      this.$router.push({ path: '/online/copyform/' + id })
    },
    copyConfig(id) {
      postAction(`${this.url.copyOnline}?code=${id}`).then((res) => {
        if (res.success) {
          this.$message.success('复制成功')
          this.loadData()
        } else {
          this.$message.error('复制失败>>' + res.message)
        }
      })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
<style lang="less">
.ant-col-push-17 .ant-col-14 {
  width: 100%;
}
.ant-card-body .table-operator {
  margin-bottom: 18px;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 15px;
  padding-bottom: 15px;
}

.anty-row-operator button {
  margin: 0 5px;
}

.ant-btn-danger {
  background-color: #ffffff;
}

.ant-modal-cust-warp {
  height: 100%;
}

.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto;
}

.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden;
}

.valid-error-cust {
  .ant-select-selection {
    border: 2px solid #f5222d;
  }
}
</style>

